package com.driving.single.common.utils;

import com.driving.single.common.exception.DrivingException;
import com.driving.single.frontend.user.dto.param.AccountParam;
import com.driving.single.frontend.user.dto.param.PhoneRegisterParam;
import org.apache.commons.lang.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * [正则表达式]验证 工具类
 *
 * @author xsfno1
 * @version v1.0.0
 * @date 2020/2/20
 **/
public class RegexUtils {

    private static final String PHONE_REGEX = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|" +
            "(18[0-9])|(19[8|9]))\\d{8}$";

    /**
     * 手机号正则验证
     *
     * @param phone 手机号
     * @return boolean
     */
    private static boolean isPhone(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return false;
        }
        Pattern p = Pattern.compile(PHONE_REGEX);
        Matcher m = p.matcher(phone);
        return m.matches();
    }

    /**
     * 手机号正则验证,错误报异常
     *
     * @param phone 手机号
     */
    public static void verifyPhone(String phone) {
        if (!RegexUtils.isPhone(phone)) {
            throw new DrivingException("请输入正确的手机号码！");
        }
    }

    /**
     * 密码验证,错误报异常
     *
     * @param password 手机号
     */
    private static void verifyPassword(String password) {
        if (StringUtils.isEmpty(password) || password.length() < 6) {
            throw new DrivingException("请输入合法的密码参数！");
        }
    }

    /**
     * 验证码验证,错误报异常
     *
     * @param code 验证码
     */
    private static void verifyCode(String code) {
        if (StringUtils.isEmpty(code) || code.length() != 4) {
            throw new DrivingException("请输入合法的验证码参数！");
        }
    }

    /**
     * 用户名验证,错误报异常
     *
     * @param username 用户名
     */
    public static void verifyUsername(String username) {
        if (StringUtils.isEmpty(username)) {
            throw new DrivingException("请输入合法的用户名！");
        }
    }


    /**
     * [账号登录]参数正则验证,错误报异常
     *
     * @param accountParam {@link AccountParam}
     */
    public static void verifyAccountLoginParam(AccountParam accountParam) {
        RegexUtils.verifyPhone(accountParam.getAccount());
        RegexUtils.verifyPassword(accountParam.getPassword());
    }


    /**
     * [手机][注册]参数正则验证,错误报异常
     *
     * @param phoneRegisterParam {@link PhoneRegisterParam} 用户[手机短信]注册参数类
     */
    public static void verifyPhoneRegisterParam(PhoneRegisterParam phoneRegisterParam) {
        RegexUtils.verifyPhone(phoneRegisterParam.getPhone());
        RegexUtils.verifyCode(phoneRegisterParam.getCode());
        RegexUtils.verifyPassword(phoneRegisterParam.getPassword());
    }
}
